﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Metadata.Util;
using Kingdee.BOS.Core.Msg;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Drivers;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.FIN.App.Core.Match.Object;
using LiMinCRMPlugin.InterfaceDocking;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.MessageCenter.Model;
using Kingdee.BOS.MessageCenter.ServiceHelper;
using Kingdee.BOS.Core.MessageCenter;
using Kingdee.BOS.BusinessEntity.MessageCenter;

namespace LiMinCRMPlugin
{
    // <summary>
    /// 查询CRM技术指标数据，如果最近存在更新，则进行联查消息通知
    /// </summary>
    /// <remarks>
    /// 功能：查询CRM技术指标数据，如果最近存在更新，则进行联查消息通知
    /// 创建人：mey
    /// 创建日期：2024年5月22日
    /// </remarks>
    [Description("技术指标消息通知")]
    [Kingdee.BOS.Util.HotUpdate]
    public class TechnicalPlan : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            //查询crm技术指标确认表，如果有更新的，就进行循环
            var sql = @"/*dialect*/ select * from CRM_V_Technical";

            DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                #region  1个技术指标改变，组合关联的生产订单发送
                if (1 != 1)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        var sql_1 = @"/*dialect*/ SELECT " +
                        " FPlannerID, STUFF((SELECT ', ' + FBILLNO FROM  T_PRD_MO a,T_PRD_MOENTRY b where a.fid=b.fid and  and c.FPlannerID=a.FPlannerID " +
                        " and F_QLTK_TECHNICALID='" + item["id"].ToString() + "' FOR XML PATH('')), 1, 2, '') AS MERGED_DATA FROM " +
                        " T_PRD_MO c,T_PRD_MOENTRY d where c.fid = d.fid and F_QLTK_TECHNICALID = '" + item["id"].ToString() + "'  " +
                        "  GROUP BY FPlannerID";

                        //销售订单技术指标确认ID下推到生产订单，查询是否有关联的生产订单
                        DataTable dt_1 = DBUtils.ExecuteDataSet(ctx, sql_1).Tables[0];
                        if (dt_1 != null && dt_1.Rows.Count > 0)
                        {
                            foreach (DataRow item_1 in dt_1.Rows)
                            {
                                if (item_1["FPlannerID"].ToString() != "0")
                                {


                                    //根据计划员查询用户
                                    var sql_2 = @"/*dialect*/ select FUSERID from T_SEC_user where FLinkObject in (select FPERSONID from T_BD_STAFF where FSTAFFID in
			                    (select FSTAFFID from   V_BD_PLANNER where fid = '" + item_1["FPlannerID"].ToString() + "'))";
                                    //销售订单技术指标确认ID下推到生产订单，查询是否有关联的生产订单
                                    DataTable dt_2 = DBUtils.ExecuteDataSet(ctx, sql_2).Tables[0];
                                    if (dt_2 != null && dt_2.Rows.Count > 0)
                                    {
                                        string messageId = SequentialGuid.NewGuid().ToString();
                                        SimpleTextMessageSendInfo simpleTextMsgSendInfo = new SimpleTextMessageSendInfo();
                                        simpleTextMsgSendInfo.Content = "关联生产订单号：" + item_1["MERGED_DATA"].ToString() + "请注意查阅！";
                                        simpleTextMsgSendInfo.Title = "技术指标变动通知";
                                        simpleTextMsgSendInfo.MsgType = (int)MessageCenterMessageType.Bussines;  //消息类别
                                        simpleTextMsgSendInfo.Level = (int)MessageLevel.Normal;                  //消息等级
                                        simpleTextMsgSendInfo.SenderId = 16394;                                  //消息发送人UserID
                                        List<int> channelList = new List<int>();
                                        channelList.Add((int)MessageChannelType.MessageCenter);     //消息通道
                                        simpleTextMsgSendInfo.ReceiverIds = new long[] { Convert.ToInt32(dt_2.Rows[0]["FUSERID"]) };  //消息接收人UserID
                                        simpleTextMsgSendInfo.Channels = channelList.ToArray();     //消息通道
                                        simpleTextMsgSendInfo.SourceNumber = "XXLY000001";  //消息来源编码，单独新建一个
                                        if (item_1["MERGED_DATA"].ToString() != "")
                                        {
                                            string[] arrstring = item_1["MERGED_DATA"].ToString().Split(',');
                                            if (arrstring.Length > 0)
                                            {
                                                var sql_3 = @"/*dialect*/ select fid from T_PRD_MO where FBillNo='" + arrstring[0].ToString() + "'";
                                                //销售订单技术指标确认ID下推到生产订单，查询是否有关联的生产订单
                                                DataTable dt_3 = DBUtils.ExecuteDataSet(ctx, sql_3).Tables[0];
                                                if (dt_3 != null && dt_3.Rows.Count > 0)
                                                {

                                                    simpleTextMsgSendInfo.LinkPKId = dt_3.Rows[0]["FID"].ToString();       //消息业务对象内码    
                                                    simpleTextMsgSendInfo.ObjectTypeId = "PRD_MO";   //消息业务对象FormID
                                                }

                                            }

                                        }

                                        MessageSendServiceHelper.AsyncSendSimpleTextMessage(ctx, simpleTextMsgSendInfo);

                                        //发送成功后插入发送成功记录，以防后续重复发送
                                        string sql_in = "insert into CRMTechnical(CRMId,Fstatus,FDate) values('" + item["id"].ToString() + "','1','" + item["modedatamodifydatetime"].ToString() + "')";
                                        DBUtils.Execute(ctx, sql_in);
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                #region  1个技术指标改变，组合关联的生产订单发送
                foreach (DataRow item in dt.Rows)
                {
                    var sql_1 = @"/*dialect*/  select FPlannerID,FBILLNO from T_PRD_MO a,T_PRD_MOENTRY b,T_PRD_MOENTRY_A c where a.FID=b.FID and b.FENTRYID=c.FENTRYID and c.FSTATUS<>'5'
                     and c.FSTATUS<>'6' and c.FSTATUS<>'7' and FPlannerID<>0  and F_QLTK_TECHNICALID = '" + item["id"].ToString() + "' " +
                     " and a.FDOCUMENTSTATUS='C' and a.FCancelStatus='A' " +
                     " order by FPlannerID,FBILLNO";

                    //销售订单技术指标确认ID下推到生产订单，查询是否有关联的生产订单
                    DataTable dt_1 = DBUtils.ExecuteDataSet(ctx, sql_1).Tables[0];
                    if (dt_1 != null && dt_1.Rows.Count > 0)
                    {
                        foreach (DataRow item_1 in dt_1.Rows)
                        {
                            if (item_1["FPlannerID"].ToString() != "0")
                            {


                                //根据计划员查询用户
                                var sql_2 = @"/*dialect*/ select FUSERID from T_SEC_user where FLinkObject in (select FPERSONID from T_BD_STAFF where FSTAFFID in
			                    (select FSTAFFID from   V_BD_PLANNER where fid = '" + item_1["FPlannerID"].ToString() + "'))";
                                //销售订单技术指标确认ID下推到生产订单，查询是否有关联的生产订单
                                DataTable dt_2 = DBUtils.ExecuteDataSet(ctx, sql_2).Tables[0];
                                if (dt_2 != null && dt_2.Rows.Count > 0)
                                {
                                    string messageId = SequentialGuid.NewGuid().ToString();
                                    SimpleTextMessageSendInfo simpleTextMsgSendInfo = new SimpleTextMessageSendInfo();
                                    simpleTextMsgSendInfo.Content = "关联生产订单号：" + item_1["FBILLNO"].ToString() + "请注意查阅！";
                                    simpleTextMsgSendInfo.Title = "技术指标变动通知";
                                    simpleTextMsgSendInfo.MsgType = (int)MessageCenterMessageType.Bussines;  //消息类别
                                    simpleTextMsgSendInfo.Level = (int)MessageLevel.Normal;                  //消息等级
                                    simpleTextMsgSendInfo.SenderId = 16394;                                  //消息发送人UserID
                                    List<int> channelList = new List<int>();
                                    channelList.Add((int)MessageChannelType.MessageCenter);     //消息通道
                                    simpleTextMsgSendInfo.ReceiverIds = new long[] { Convert.ToInt32(dt_2.Rows[0]["FUSERID"]) };  //消息接收人UserID
                                    simpleTextMsgSendInfo.Channels = channelList.ToArray();     //消息通道
                                    simpleTextMsgSendInfo.SourceNumber = "XXLY000001";  //消息来源编码，单独新建一个
                                    if (item_1["FBILLNO"].ToString() != "")
                                    {

                                        var sql_3 = @"/*dialect*/ select fid from T_PRD_MO where FBillNo='" + item_1["FBILLNO"].ToString() + "'";
                                        //销售订单技术指标确认ID下推到生产订单，查询是否有关联的生产订单
                                        DataTable dt_3 = DBUtils.ExecuteDataSet(ctx, sql_3).Tables[0];
                                        if (dt_3 != null && dt_3.Rows.Count > 0)
                                        {

                                            simpleTextMsgSendInfo.LinkPKId = dt_3.Rows[0]["FID"].ToString();       //消息业务对象内码    
                                            simpleTextMsgSendInfo.ObjectTypeId = "PRD_MO";   //消息业务对象FormID
                                        }

                                    }

                                    MessageSendServiceHelper.AsyncSendSimpleTextMessage(ctx, simpleTextMsgSendInfo);

                                    //发送成功后插入发送成功记录，以防后续重复发送
                                    string sql_in = "insert into CRMTechnical(CRMId,Fstatus,FDate) values('" + item["id"].ToString() + "','1','" + item["modedatamodifydatetime"].ToString() + "')";
                                    DBUtils.Execute(ctx, sql_in);
                                }
                            }
                        }
                    }
                }
                #endregion
            }
        }
    }
}